package com.weiyan.controller;

import com.weiyan.domian.Order;
import com.weiyan.domian.Product;
import com.weiyan.server.OrderServer;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author misterWei
 * @create 2020年02月20号:20点19分
 * @mailbox mynameisweiyan@gmail.com
 */
@RestController
@CrossOrigin
@RequestMapping("order")
public class OrderController {
/*    @Autowired
    private RestTemplate restTemplate;*/

    @Autowired
    private OrderServer orderServer;

    @Reference // 演示
    private com.weiyan.service.ProductService productServer;

    // 这个对象用来获取所有注册服务的实例

    @Autowired
    private DiscoveryClient discoveryClient;

    //下订单服务
    @RequestMapping(value = "addOrder/{pid}",method = RequestMethod.GET)
    public Order addOrder(@PathVariable Integer pid){
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
/*
        Product product = restTemplate.getForObject("http://service-product/product/findByPid/" + pid, Product.class);
*/
        Product  product = productServer.findByPid(pid);
        if (product == null){
            return new Order();
        }
        Order order = new Order();
        order.setNumber(1);
        order.setUid(1);
        order.setUsername("test");
        order.setPid(pid);
        order.setPname(product.getPname());
        orderServer.save(order);


        return order;
    }

    //测试容错规则
    @RequestMapping(value = "message1",method = RequestMethod.GET)
     public String message1(){
        orderServer.message();
        return "message1";
    }

    //测试容错规则
    @RequestMapping(value = "message2",method = RequestMethod.GET)
    public String message2(){
        orderServer.message();
        return "message2";
    }



}
